package com.songcan.oauth.provider;

import com.songcan.common.vo.UserDetailsNew;
import com.songcan.oauth.other.CoreLoginAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


@Slf4j
@Order(3)
public class CoreAuthenticationProvider extends DaoAuthenticationProvider {





    public CoreAuthenticationProvider() {
        log.info("MobileLoginAuthenticationProvider loading ...");
    }


    /**
     * 认证
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取过滤器封装的token信息
        System.out.println("认证:{}" + authentication.getPrincipal());
        CoreLoginAuthenticationToken authenticationToken = (CoreLoginAuthenticationToken) authentication;
        //获取用户信息（数据库认证）
        UserDetailsNew userDetails = (UserDetailsNew) authentication.getPrincipal();


        //不通过
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("账户token已过期");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("账户已锁");
        } else if (!userDetails.isCredentialsNonExpired()) {
            log.debug("User account credentials have expired");
            throw new CredentialsExpiredException(
                    "账号未激活，请注册后登录");
        }else if(!userDetails.isEnabled()){
            throw new CredentialsExpiredException("账号为启用");
        }


        //通过
        CoreLoginAuthenticationToken authenticationResult = new CoreLoginAuthenticationToken(userDetails, authenticationToken.getType());
        authenticationResult.setBindMobile(((CoreLoginAuthenticationToken) authentication).getBindMobile());
        return authenticationResult;
    }

    /**
     * 根据token类型，来判断使用哪个Provider
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return CoreLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }




}
